package com.trip.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * String Utils
 * 
 * @author hc24
 * 
 */
public class StringUtil {
	
	private static final String UNDERLINE="_";
	
	private StringUtil(){}
	

	public synchronized static String format(String s,String ocharSet,String ncharSet){
		try {
			return s==null?s:new String(s.getBytes(ocharSet),ncharSet);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
	

	public static String format(String s){
		return format(s,"ISO-8859-1","UTF-8");
	}


	public static String md5(String s){
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
		md.update(s.getBytes());
		byte[] b = md.digest();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			hex = (hex.length()==1?"0":"")+hex;
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}
	

    public static String ajax(String s){
        try {
			return null==s?null:java.net.URLDecoder.decode(s,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
    }
    

    public static String formatNumber(double f, String pattern) {  
        DecimalFormat num = new DecimalFormat(pattern);
        return num.format(f);  
    }
    

    public static String pattern(String str,String regex){
    	Pattern p=Pattern.compile(regex);
    	Matcher m=p.matcher(str);
    	if(m.find()){
    		return m.group();
    	}
    	return null;
    }
    

    public static boolean isNumeric(String str){
    	 Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+"); 
    	   Matcher isNum = pattern.matcher(str);
    	   if( !isNum.matches() ){
    	       return false; 
    	   } 
    	   return true; 
    }
    

    public static boolean isEmpty(String str){
    	return str==null||"".equals(str.trim());
    }
    
    public static String[] split(String toSplit, String delimiter) {
		int offset = toSplit.indexOf(delimiter);
		if (offset < 0) {
			return null;
		}
		String beforeDelimiter = toSplit.substring(0, offset);
		String afterDelimiter = toSplit.substring(offset + delimiter.length());
		return new String[] {beforeDelimiter, afterDelimiter};
	}
    

    public static String[] splitCamel(String param){
    	List<String> list=new ArrayList<>();
    	
		int preStart=0;
		for(int i=0;i<param.length();i++){
			if(Character.isUpperCase(param.charAt(i))&&i!=0){
				list.add(param.substring(preStart,i));
				preStart=i;
			}
		}
		if(preStart==0)
			list.add(param);
		else
			list.add(param.substring(preStart));
		
		return list.toArray(new String[]{});
    }

    public static String camelToUnderline(String param,boolean isToUpper){
        if (param==null||"".equals(param.trim())){
            return "";
        }
        int len=param.length();
        StringBuilder sb=new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c=param.charAt(i);
            if (Character.isUpperCase(c)&&i!=0){
                sb.append(UNDERLINE);
                sb.append(Character.toLowerCase(c));
            }else{
                sb.append(c);
            }
        }
        return isToUpper?sb.toString().toUpperCase():sb.toString();
    }
    

    public static String underlineToCamel(String param){
        if (param==null||"".equals(param.trim())){
            return "";
        }
        String[] words=param.split(UNDERLINE);
		StringBuilder sb=new StringBuilder();
		sb.append(words[0].toLowerCase());
		for(int i=1;i<words.length;i++){
			sb.append(words[i].substring(0,1).toUpperCase()+words[i].substring(1).toLowerCase());
		}
		return sb.toString();
    }
    

    public static String clearControlChar(String str){
    	char[] chars= str.toCharArray();
    	List<Character> newChars=new ArrayList<>(chars.length);
    	for(int i=0;i<chars.length;i++){
    		if(!(chars[i]>=0&&chars[i]<=31)){
    			newChars.add(chars[i]);
    		}
    	}
    	
    	char[] charArray=new char[newChars.size()];
    	for(int i=0;i<newChars.size();i++)
    		charArray[i]=newChars.get(i);
    	
    	return String.valueOf(charArray);
    }
    
    
    public static void main(String[] args) {
		System.out.println(md5("111"));
		System.out.println(isNumeric("5.0"));
		
		System.out.println(underlineToCamel("User_Name"));
		System.out.println(camelToUnderline("User",true));
		System.out.println(Arrays.toString(splitCamel("UsernameAndPassword")));
		
		System.out.println(clearControlChar("asdf asdf23"));

		System.out.println(md5("12345a").substring(0,30));
	}
	
}